package com.ruoyi.aspectj;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author 蒋翔 SY100242
 * @date 2024/7/22 10:19
 * @email SY100242@hnlens.com
 */
@Component
@Aspect
@Slf4j
public class WebLogAspectj {

    private Long startTime;

    private Long endTime;

    @Pointcut("execution(public * com.ruoyi..controller..*.*(..))")
    public void doPoint() {
    }

    @Before("doPoint()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            startTime = System.currentTimeMillis();
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(requestAttributes != null) {
                HttpServletRequest request = requestAttributes.getRequest();
                log.info("请求开始时间:{}", LocalDateTime.now());
                log.info("\r\nRequest URI:{}\r\nRequest Method : {}\r\nRequest params:{}", request.getRequestURI(), request.getMethod(), Arrays.toString(joinPoint.getArgs()));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @AfterReturning(pointcut = "doPoint()",returning = "returnValue")
    public void doAfterReturn(Object returnValue) throws Throwable {
        try {
            endTime = System.currentTimeMillis();
            log.info("请求结束时间:{}", LocalDateTime.now());
            log.info("请求耗时:{}毫秒", endTime - startTime);
            log.info("请求响应:{}", returnValue);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
